package com.concurrent.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author: zhouyang
 * @descrpition: 实现控制并发的限制
 * @time: 2019-05-08 11:19
 */
@Slf4j
public class SemaphoreTest {
    private static int clientTotal = 200;

    public static void main(String[] args){
        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(clientTotal);

        for(int i=0;i<clientTotal*10;++i){
            final int now = i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    //也可以一次性获取或者释放多个信号量 semaphore.acquire(N );
                    test(now);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                semaphore.release();
            });
        }
        log.info("thread finish");
        executorService.shutdown();
    }

    private static void test(final int threadNum)throws Exception{
        log.info("thread {}",threadNum);
        Thread.sleep(2000);
    }
}
